package czp.progressbarhandler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;


public class TestBarHandler extends Activity {
	ProgressBar bar = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button start = (Button)findViewById(R.id.startButton);
        start.setOnClickListener(new ButtonListener());
        bar = (ProgressBar)findViewById(R.id.bar);
    }
    
    class ButtonListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			bar.setVisibility(View.VISIBLE);
			updateBarHandler.post(updateThread);
		}
    	
    }
    Handler updateBarHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			bar.setProgress(msg.arg1);
			updateBarHandler.post(updateThread);
		}
    };
    
    Runnable updateThread = new Runnable() {
		int i = 0;
		@Override
		public void run() {
			System.out.println("Begin Thread: " + i);
			i += 10;
			Message msg = updateBarHandler.obtainMessage();
			msg.arg1 = i;
			try {
				Thread.sleep(1000);
			} catch(Exception e) {
				e.printStackTrace();
			}
			updateBarHandler.sendMessage(msg);
			if(i == bar.getMax()) {
				System.out.println("remove");
				updateBarHandler.removeCallbacks(updateThread);
			}
		}
	};
}
